package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.db.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper; //日志表

    @Autowired
    private AnalysisMapper analysisMapper;//日统计表

    /**
     * 计算日志表的数据，写入到日统计表中
     * 1、日统计表tb_analysis，保存或者更新
     *      根据操作的日期，查询判断
     * 2、日统计表需要的数据来源
     *      计算tb_log表中的数据
     * 3、计算tb_log编写SQL语句？
     */
    public void analysis() throws ParseException {
        //当前时间
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //前天时间
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        //1、准备计算的数据
        //1.1、查询注册用户数
        Integer regNum = logMapper.queryByLogTimeAndType(today, "0102");
        //1.2、登陆次数
        Integer logNum = logMapper.queryByLogTimeAndType(today, "0101");
        //1.3、活跃用户数
        Integer activeNum = logMapper.queryByLogTime(today);
        //1.4、次日留存用户数
        Integer numRetention1d = logMapper.queryNumRetention1d(today, yesterday);
        //2、根据当前日志，查询统计表
        QueryWrapper<Analysis> qw = new QueryWrapper<>();
        Date recordDate = new SimpleDateFormat("yyyy-MM-dd").parse(today); //年月日
        qw.eq("record_date",recordDate);
        Analysis analysis = analysisMapper.selectOne(qw);
        //2.1 如果数据不存在，保存统计数据
        if(analysis == null) {
            analysis = new Analysis();
            analysis.setRecordDate(recordDate);
            analysis.setNumRegistered(regNum);
            analysis.setNumActive(activeNum);
            analysis.setNumLogin(logNum);
            analysis.setNumRetention1d(numRetention1d);
            analysisMapper.insert(analysis);
        }else {
            //2.2 数据存在，更新统计数据
            analysis.setNumRegistered(regNum);
            analysis.setNumActive(activeNum);
            analysis.setNumLogin(logNum);
            analysis.setNumRetention1d(numRetention1d);
            analysisMapper.updateById(analysis);
        }
    }
}
